import json
import logging

from django.http import JsonResponse
from django.shortcuts import render
from wxcloudrun.models import xiaoqu
from wxcloudrun.models import tmpobj

logger = logging.getLogger('log')

def clear():  # 删除原有的数据
    data = xiaoqu.objects.all()
    data.delete()

def savelog(str1):
    obj = tmpobj()
    obj.data = str(str1)
    obj.save()


def savedata(item):
    obj = xiaoqu()
    obj._id = item.get('_id')
    obj._openid = item.get('_openid')
    obj.insert_time = item.get('insert_time')
    obj.create_user = item.get('create_user')
    obj.finish_date = item.get('finish_date')
    obj.check_time = item.get('check_time')
    obj.name = item.get('name')
    obj.user_name = item.get('user_name')
    obj.fxs = item.get('fxs')
    obj.lous = item.get('lous')
    obj.xcs = item.get('xcs')
    obj.zhus = item.get('zhus')
    obj.save()


def adddata(request, _):
    '''
    增加小区数据
    '''
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    print(body)
    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'POST' or request.method == 'post':
        if (body['action'] == 'clear'):
            clear()  # 删除原来的数据
        if (body['action'] == 'saveall'):
            dataobj = body['data']
            for item in dataobj:
                savedata(item)
            body = {'code': 0, 'errorMsg': ''}

        rsp = JsonResponse(body, json_dumps_params={'ensure_ascii': False})
    else:
        rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                           json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))

    return rsp

